package cn.knight.mq.easy;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListener;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
* @Description: 生产者
* @Author: Winnie
* @Version: 1.0
* @Date:  2022/7/25 12:52
  */
public class Consumer {
    public static void main(String[] args) throws Exception {
        // 创建消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("snyc_hello_group");

        // 连接mq
        consumer.setNamesrvAddr("127.0.0.1:9876");

        // 订阅消息
        consumer.subscribe("hello_topic","hello_tags");

        // 注册监听器，进行消息获取
        consumer.registerMessageListener((List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext)-> {
            for (MessageExt messageExt : list) {
                // 遍历获取消息
                String result = new String(messageExt.getBody(), StandardCharsets.UTF_8);
                System.out.println(result);
            }
            // 消息是否已经被消费
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        );

        // 启动消费者
        consumer.start();
    }
}
